import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";

let ROOT = "http://192.168.37.41:8989";
// if (process.env.NODE_ENV === "production") {
//   ROOT = "http://lfa.api.longhu.net:10080";
// } else {
//   ROOT = "http://10.231.32.34:8080";
// }
Vue.use(VueAxios, axios);
Vue.axios.defaults.baseURL = ROOT;

/**
 * sendPost请求
 * @param url
 * @param params 参数默认为空对象
 * @returns {Promise}
 */
export function sendPost(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data)
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * sendGet请求
 * @param url
 * @param params 参数默认为空对象
 * @returns {Promise}
 */
export function sendGet(url, data = {}) {
  return new Promise((resolve, reject) => {
    // console.log(data, '3212313213213132133');
    axios
      .get(url, data)
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}

// http request拦截器
Vue.axios.interceptors.request.use(
  config => {
    // Do something before request is sent
    const token = localStorage.token;
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// http response 拦截器
Vue.axios.interceptors.response.use(
  response => {
    if (response.data.code === "403") {
      console.log("token失效")
    } else {
      return response;
    }
  },
  error => {
    return Promise.reject(error);
  }
);
// export default axios;
